<template>
  <div class="page">
    <h2>任务列表页面</h2>
    <el-select
      v-model="selectSource"
      placeholder="Select"
      size="large"
      style="width: 240px"
      @change="handleSelectChange"
    >
      <el-option
        v-for="item in allSource"
        :key="item"
        :label="item"
        :value="item"
      />
    </el-select>
    <el-button link type="primary" size="large" @click="addNewTask">新增任务</el-button>

    <el-table :data="taskList" stripe style="width: 100%">
      <el-table-column prop="taskName" label="任务名称" />
      <el-table-column prop="source" label="任务来源" />
      <el-table-column prop="status" label="是否完成" />
      <el-table-column label="操作" min-width="120">
        <template #default="{ row }">
          <el-tooltip content="任务已完成，不可操作" :disabled="!row.status">
            <el-button 
              link 
              type="primary" 
              size="small" 
              :disabled="row.status"
              @click="fixTask(row.id)"
              :class="{ 'disabled-button': row.status }"
            >
              完成
            </el-button>
          </el-tooltip>
          <el-button link type="primary" size="small" @click="queryById(row.id)"
            >查看</el-button
          >
          <el-button link type="primary" size="small" @click="addRemark(row.id)"
            >添加备注</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" title="新增任务">
      <el-form :model="newTaskForm" label-width="120px">
        <el-form-item label="任务名称">
          <el-input v-model="newTaskForm.taskName"></el-input>
        </el-form-item>
        <el-form-item label="任务来源">
          <el-select v-model="newTaskForm.source" placeholder="请选择" allow-create filterable>
            <el-option v-for="item in allSource" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveNewTask">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onActivated } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import TaskDetailTable from "./TaskDetailTable.vue";
import { h } from "vue";
import { BASE_URL, API_PATH } from "@/config/api";

// 新增表单数据
const newTaskForm = ref({ taskName: '', source: '' });
// 控制对话框显示
const dialogVisible = ref(false);
// 来源列表
const allSource = ref([]);
// 被选中的来源
const selectSource = ref("");
// 计划
const taskList = ref([]);
const loading = ref(false);

const queryAllSource = async () => {
  try {
    loading.value = true;
    const response = await axios.get(
      `${BASE_URL}${API_PATH.task.queryAllSource}`
    );
    allSource.value = response.data;
  } catch (error) {
    ElMessage.error("获取任务类型失败：" + error.message);
  } finally {
    loading.value = false;
  }
};

const queryTask = async () => {
  try {
    loading.value = true;
    const response = await axios.get(
      `${BASE_URL}${API_PATH.task.query}/` + selectSource.value
    );
    taskList.value = response.data;
  } catch (error) {
    ElMessage.error("获取任务失败：" + error.message);
  } finally {
    loading.value = false;
  }
};

const handleSelectChange = (value) => {
  queryTask();
};

const fixTask = async (id) => {
  try {
    loading.value = true;
    const response = await axios.get(
      `${BASE_URL}${API_PATH.task.updateStatus}/` + id
    );
    queryTask();
    console.log(response);
  } catch (error) {
    ElMessage.error("更新状态失败：" + error.message);
  } finally {
    loading.value = false;
  }
};

const queryById = async (id) => {
  console.log(id);
  try {
    loading.value = true;
    const response = await axios.get(
      `${BASE_URL}${API_PATH.task.queryById}/` + id
    );
    const viewData = response.data
    console.log(viewData)
    ElMessageBox.alert('任务详情',h(TaskDetailTable, { taskData: viewData }),{
      confirmButtonText:'关闭',
      customClass: 'task-detail-dialog',
      width: '60%',
      callback:(action) =>{
        ElMessage({
          type:'info',
          message:'关闭了'
        })
      }
    });
  } catch (error) {
    ElMessage.error("任务失败：" + error.message);
  } finally {
    loading.value = false;
  }
};

const addRemark = async (id) => {

  ElMessageBox.prompt('新备注：','备注',{
    confirmButtonText:'OK',
  }).then(async ({value}) =>{
    const requestData = {
        'id':id,
        'remark':value,
      }
    await axios.post(`${BASE_URL}${API_PATH.task.addRemark}`,requestData);
    ElMessage({
        type: 'success',
        message: '备注添加成功',
      })
    queryTask();
  })
};

const addNewTask = () => {
  dialogVisible.value = true;
};

const saveNewTask = async () => {
  try {
    loading.value = true;
    console.log(newTaskForm.value)
    await axios.post(`${BASE_URL}${API_PATH.task.create}`, newTaskForm.value);
    ElMessage.success('任务添加成功');
    newTaskForm.value = { taskName: '', source: '' };
    dialogVisible.value = false;
    queryTask();
  } catch (error) {
    ElMessage.error('任务添加失败：' + error.message);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  queryAllSource();
  queryTask();
});

onActivated(() => {
  queryAllSource();
  queryTask();
});
</script>

<style scoped>
.disabled-button {
  color: #a8abb2 !important;
  cursor: not-allowed !important;
}

/* .task-detail-dialog .el-table {
  border: none;
  margin: -10px;
}
.task-detail-dialog .el-table td,
.task-detail-dialog .el-table th {
  border-bottom: none;
}
.task-detail-dialog .el-table__header-wrapper {
  border-bottom: 1px solid #ebeef5;
} */
</style>